package com.it;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class _6_4ServletConfigTest1 extends HttpServlet {
    //获取参数:
    // 1、声明ServletConfig属性和ServletContext属性
    private ServletConfig config;
    private ServletContext context;
    //2、初始化ServletConfig属性（和6-3初始化参数一样）
    public void init(ServletConfig config) throws ServletException {
        super.init();
        this.config=config;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //3、通过ServletConfig对象的getServletContext获取ServletContext属性并赋值
        context = this.config.getServletContext();
        //4、通过ServletContext对象的getInitParameter方法获取上下文参数
        String username = this.context.getInitParameter("username");
        String password = this.context.getInitParameter("password");
        String url = this.context.getInitParameter("url");
        //设置响应字符集格式为UTF-8
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        //返回一个PrintWriter对象，Servlet使用它来输出字符串形式的正文数据
        PrintWriter out = response.getWriter();
        //以下为输出的HHTML正文数据
        out.println("<HTML>");
        out.println("<HEAD><TITLE>ServletContext</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("获取连接数据库的初始化参数："+"<br/>");
        out.println("url："+url+"<br/>");
        out.println("username："+username+"<br/>");
        out.println("password："+password+"<br/>");
        out.println("</BODY>");
        out.println("</HTML>");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
